/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *PmBudgetApplyController
 * 项目预算申请单
 *
 * 修改纪录
 * 2020-05-22 版本：1.0 shenyouyi 创建。
 * @version 版本：1.0
 * @author 作者：shenyouyi
 * 创建日期：2020-05-22
 */

package com.topscomm.pm.controller;

import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.pm.controller.auto.PmBudgetApplyControllerAuto;
import com.topscomm.pm.pojo.PmBudgetLineEntity;
import com.topscomm.pm.pojo.PmProjectEntity;
import com.topscomm.pm.service.IPmBudgetLineService;
import com.topscomm.pm.service.IPmProjectService;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.TapSystemConst;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: shenyouyi
 * @date: 2020-05-22
 * @description:项目预算申请单Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/budgetApply")
public class PmBudgetApplyController extends PmBudgetApplyControllerAuto implements IPmBudgetApplyController {

	@Autowired
	private IPmProjectService pmProjectService;
	@Autowired
	private IPmBudgetLineService pmBudgetLineService;

	/**
	 * @author: shenyouyi
	 * @date: 2020-05-22
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" PmBudgetApply.enabled=1 ");
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmBudgetApply.state={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmBudgetApply.docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmBudgetApply.docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmBudgetApply.docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (PmBudgetApply.deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (PmBudgetApply.username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmBudgetApply.deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_projectid")) {
			String value = paraMap.get("qry_projectid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmBudgetApply.projectid={0}", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		sql .appendSingle(this.spellingSqlForProject(paraMap, "PmBudgetApply","projectid","id"));
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession)) {
				sql.appendSingle(" and (" + MisStringUtil.createWhereByUsercodeFromProject(
						this.getUserBean().getUser(), "projectid",
						service.getDao().getTableName()) +
								" or PmBudgetApply.usercode = '{0}')",
						this.getUserBean().getUser().getCode());
			}  else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020-05-22
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: shenyouyi
	 * @date: 2020-05-22
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目预算申请单申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
		List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmBudgetApply", dataMap.get("deptcode").toString(),dataMap.get("usercode").toString(),null, "sortcode");
		Long flowid = flowidList.size()>0? ConvertUtil.convertToLong(flowidList.get(0).get("id")) :null;
		dataMap.put("flowid", flowid);
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 取消审批
	  **/
	@DeleteMapping({"/delApproval"})
	public ResponseResult<Object> delApproval(@RequestBody(required = false) Map<String, Object> paraMap) {
		ResponseResult responseResult = super.delApproval(paraMap);
		if(responseResult.isSuccess()){
			String id = ConvertUtil.convertToString(paraMap.get("id"));
			this.service.updateBudgetMoneyOfProjectBase(id, 0);
			return ResponseResult.ok("取消审批成功");
		}
		return responseResult;
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 设置显示字段
	  **/
	@Override
	protected void afterLoad(Map<String, Object> paraMap) {
		super.afterLoad(paraMap);
		PmProjectEntity pmProjectEntity = pmProjectService.queryById(paraMap.get("projectid").toString());
		// 计算当前毛利率和预计毛利率
		String grossmargin = "";
		BigDecimal projectmoney = pmProjectEntity.getProjectmoney();
		BigDecimal budgetmoney = pmProjectEntity.getBudgetmoney();
		DecimalFormat df = new DecimalFormat("0.00%");
		if(projectmoney!=null && budgetmoney!=null && projectmoney.compareTo(BigDecimal.ZERO)>0){
			BigDecimal grossMarginBd = projectmoney.subtract(budgetmoney).divide(projectmoney, 4, BigDecimal.ROUND_HALF_UP);
			grossmargin = df.format(grossMarginBd);
		}
		// 计算预计毛利率
		String estimatedgrossmargin = grossmargin;
		int state = Integer.valueOf(paraMap.get("state").toString());
		if(state != TapSystemConst.TapApprovalBillStateEnum.Approved){// 审批不通过
			long id = Long.valueOf(paraMap.get("id").toString());
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle("budgetapplyid = {0}", id);
			List<String> queryFields = new ArrayList<>();
			queryFields.add("sum(budgetmoney) as totalmoney");
			List<Map<String,Object>> budgetMoneyList = pmBudgetLineService.queryMapFieldsByWhere(sql.toString(), queryFields);
			if(budgetMoneyList.size()>0 && budgetMoneyList.get(0)!=null) {
				BigDecimal totalMoney = (BigDecimal) budgetMoneyList.get(0).get("totalmoney");
				if(projectmoney!=null && budgetmoney!=null && projectmoney.compareTo(BigDecimal.ZERO)>0){
					BigDecimal estimatedGrossMarginBd = projectmoney.subtract(budgetmoney).subtract(totalMoney).divide(projectmoney, 4, BigDecimal.ROUND_HALF_UP);
					estimatedgrossmargin = df.format(estimatedGrossMarginBd);
				}
			}
		}
		paraMap.put("grossmargin", grossmargin);
		paraMap.put("estimatedgrossmargin", estimatedgrossmargin);
	}


	@Override
	@GetMapping({"/list"})
	public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			paraMap.put("whereSql",sqlWhere);
			int totalCount = this.service.getCount(paraMap,"getBudgetAndProjectCount");
			List<Map<String, Object>> tempList = null;
			HashMap<String, Object> paraMap2 = new HashMap<>();
			paraMap2.put("curPageIndex",query.getCurrentPage());
			int beginCount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
			paraMap2.put("begincount",beginCount);
			paraMap2.put("pagesize", query.getPageSize());
			paraMap2.put("sidx", query.getSidx());
			paraMap2.put("sord", query.getSord());
			paraMap2.put("whereSql", sqlWhere);
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(paraMap2,"getPmBudgetAndProject");
			} else {
				tempList = this.service.queryMap(paraMap2,"queryMapByWhere1");
			}
			this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}
}

